package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.yupi.yupicturebackend.common.UserHolder;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.manager.FileManger;
import com.yupi.yupicturebackend.manager.upload.FilePicutreUpload;
import com.yupi.yupicturebackend.manager.upload.PictureUploadTemplate;
import com.yupi.yupicturebackend.manager.upload.URLPicutreUpload;
import com.yupi.yupicturebackend.mapper.PictureMapper;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import com.yupi.yupicturebackend.model.dto.picture.PictureQueryRequest;
import com.yupi.yupicturebackend.model.dto.picture.PictureReviewRequest;
import com.yupi.yupicturebackend.model.dto.picture.PictureUploadRequest;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.PictureStatusEnum;
import com.yupi.yupicturebackend.model.enums.UserRoleEnum;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-04-30 23:00:11
*/
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService {
    @Resource
    private URLPicutreUpload urlPicutreUpload;
    @Resource
    FilePicutreUpload filePicutreUpload;
    @Resource
    private UserService userService;


    public PictureVO uploadPicture(Object inputStream, PictureUploadRequest request, User loginuser) {
        //判断用户是否存在
        if (loginuser == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR,"未登录");
        }
        //判断用户是否是更新
        Long PictureId = null;
        if(request.getId() != null){
            PictureId = request.getId();
            boolean exists = this.lambdaQuery().eq(Picture::getId, PictureId).exists();
            if(!exists){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片不存在");
            }
        }
        //上传图片
        Picture picture = new Picture();
        String prefix = String.format("public/%s", PictureId);
        PictureUploadTemplate pictureUploadTemplate = filePicutreUpload;
        if(inputStream instanceof String){
            pictureUploadTemplate = urlPicutreUpload;
        }
        UploadPictureResult result = null;
        try {
            result = pictureUploadTemplate.uploadPicture(inputStream,prefix);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图片上传失败");
        }
        //返回封装图片结果
        if(PictureId != null){
            picture.setId(PictureId);
            picture.setEditTime(new Date());
        }
        //封装上传的图片信息
        picture.setUrl(result.getUrl());
        picture.setName(result.getPicName());
        picture.setPicSize(result.getPicSize());
        picture.setPicWidth(result.getPicWidth());
        picture.setPicHeight(result.getPicHeight());
        picture.setPicScale(result.getPicScale());
        picture.setPicFormat(result.getPicFormat());
        picture.setUserId(1L);
        EditReview(picture);

        //上传到数据库
        boolean uploadresult = this.saveOrUpdate(picture);
        if (!uploadresult){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"图片上传失败");
        }
        return PictureVO.objToVo(picture);
    }



    @Override
    public QueryWrapper<Picture> Query_Wrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if(pictureQueryRequest == null){
            return queryWrapper;
        }
        //get select condition parameters
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        //searchtext fuzzy query
        if (searchText != null){
            queryWrapper.and(qw -> qw.like("name",searchText)).or().like("introduction",searchText);
        }
        //is not null concatenate query
        queryWrapper.eq(ObjectUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjectUtil.isNotEmpty(reviewStatus),"reviewStatus",reviewStatus);
        queryWrapper.eq(ObjectUtil.isNotEmpty(reviewerId),"reviewerId",reviewerId);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picSize),"picSize",picSize);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picWidth),"picWidth",picWidth);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picHeight),"picHeight",picHeight);
        queryWrapper.eq(ObjectUtil.isNotEmpty(picScale),"picScale",picScale);
        queryWrapper.eq(ObjectUtil.isNotEmpty(userId),"userId",userId);
        queryWrapper.like(StringUtils.isNotEmpty(name),"name",name);
        queryWrapper.like(StringUtils.isNotEmpty(introduction),"introduction",introduction);
        queryWrapper.like(StringUtils.isNotEmpty(category),"category",category);
        queryWrapper.like(StringUtils.isNotEmpty(picFormat),"picFormat",picFormat);
        queryWrapper.like(StringUtils.isNotEmpty(reviewMessage),"reviewMessage",reviewMessage);


        //concatenate tags
        if(CollUtil.isNotEmpty(tags)){
            for(String tag : tags){
                queryWrapper.like("tags","\"" + tag + "\"");
            }

        }
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField),sortOrder.equals("ascend"),sortField);
        return queryWrapper;
    }

    @Override
    public PictureVO getPictureVO(Picture picture) {
        PictureVO pictureVO = PictureVO.objToVo(picture);
        Long userId = pictureVO.getUserId();
        if(userId != null && userId > 0){
            User user = userService.getById(userId);
            UserVO userVO = new UserVO();
            BeanUtil.copyProperties(user,userVO);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage) {
        List<Picture> pictures = picturePage.getRecords();
        Page<PictureVO> page = new Page<>(picturePage.getCurrent(), picturePage.getSize(),picturePage.getTotal());
        if (!ObjectUtil.isNotEmpty(picturePage)){
            return page;
        }
        //图片对象=》封装图片对象
        List<PictureVO> pictureVOS = pictures.stream().map(PictureVO::objToVo).collect(Collectors.toList());
        //用户id形成一个集合
        List<Long> userIds = pictureVOS.stream().map(p -> p.getUserId()).collect(Collectors.toList());
        Map<Long, List<User>> UserIdmaps = userService.listByIds(userIds).stream().collect(Collectors.groupingBy(User::getId));
        List<User> userList = userIds.stream().map(id -> userService.getById(id)).collect(Collectors.toList());
        //填充信息
        for (PictureVO pictureVO : pictureVOS) {
            Long userId = pictureVO.getUserId();
            if(UserIdmaps.containsKey(userId)){
                User user = UserIdmaps.get(userId).get(0);
               UserVO userVO = new UserVO();
               BeanUtil.copyProperties(user,userVO);
                pictureVO.setUser(userVO);
            }
        }
        page.setRecords(pictureVOS);
        return page;
    }

    @Override
    public void PictureReview(PictureReviewRequest reviewRequest) {
        //校验参数
        if (reviewRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"参数为空");
        }
        Long id = reviewRequest.getId();
        Integer reviewStatus = reviewRequest.getReviewStatus();
        if (id == null || reviewStatus == null || reviewStatus == PictureStatusEnum.REVIEWING.getValue()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //图片是否存在
        Picture oldpicture = this.getById(id);
        if (oldpicture == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"图片不存在");
        }
        //操作数据库
        Picture picture = new Picture();
        BeanUtil.copyProperties(oldpicture,picture);
        picture.setReviewTime(new Date());
       Long id1 = UserHolder.getUser().getId();
       picture.setReviewerId(id1);
        boolean result = this.updateById(picture);
        if (!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
    }
    public void EditReview(Picture picture){
        UserVO user = UserHolder.getUser();
        //如果是管理员自动过审
        if(user.getUserRole().equals(UserRoleEnum.ADMIN.getValue())){
            picture.setReviewStatus(PictureStatusEnum.PASS.getValue());
            picture.setReviewerId(user.getId());
            picture.setReviewTime(new Date());
            picture.setReviewMessage("管理员自动过审");
        }else {
            picture.setReviewStatus(PictureStatusEnum.REVIEWING.getValue());
        }
    }
}




